package com.CTAtracker.android.DAO;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.CTAtracker.android.DataBase.MySQLiteHelperFavorite;
import com.CTAtracker.android.Models.StopETA;

public class FavoriteDataSource {

	/**
	 * The SQLite Database
	 */
	private SQLiteDatabase database;
	/**
	 * The helper to the table line in the database
	 */
	private MySQLiteHelperFavorite dbHelperFavorite;
	
	/**
	 * Create the database helper from the context 
	 * @param context the current context 
	 */
	public FavoriteDataSource(Context context) {
		dbHelperFavorite = new MySQLiteHelperFavorite(context);
	}

	/**
	 * Open the database to be writable
	 * @throws SQLException fail to open the database
	 */
	public void open() throws SQLException {
		database = dbHelperFavorite.getWritableDatabase();
	}

	/**
	 * Close the database
	 */
	public void close() {
		dbHelperFavorite.close();
	}
	
	/**
	 * Return the list of the station's Ids of the favorites 
	 * @param database the database to find the favorites
	 * @return the list of the station's Ids of the favorites
	 */
	public ArrayList<StopETA> getAllFavoriteStops(){
		ArrayList<StopETA> favoriteStops = new ArrayList<StopETA>();
		Cursor c = database.query(
				MySQLiteHelperFavorite.TABLE_FAVORITE, 
				MySQLiteHelperFavorite.allColumns, 
				null, null, null, null, null);
		c.moveToFirst();
		while(!c.isAfterLast()){
			favoriteStops.add(cursorToStop(c));
			c.moveToNext();
		}
		return favoriteStops;
	}

	public StopETA cursorToStop(Cursor c){
		StopETA s = new StopETA();

		s.set_idStop(c.getInt(1));
		s.set_nameStop(c.getString(2));
		s.set_parentId(c.getInt(3));
		s.set_color(c.getInt(4));
		
		return s;
	}

	public void insert(StopETA stop){
		dbHelperFavorite.createFavorite(database, stop.getNameStopFavorite(), stop.get_idStop(), stop.get_parentId(), stop.getColor().getColor());
	}
	
	public void delete(StopETA stop){
		dbHelperFavorite.deleteFavorite(database, stop.get_idStop());
	}
	
	public boolean isFavorite(int stopId){
		
		Cursor cursor = database.query(
				MySQLiteHelperFavorite.TABLE_FAVORITE,
				MySQLiteHelperFavorite.allColumns, 
				MySQLiteHelperFavorite.FAVORITE_ID_STOP+"="+stopId, 
				null, null, null, null);
		cursor.moveToFirst();
		int result = cursor.getCount();
		cursor.close();
		return (result!=0);
	}
}
